package com.zf.nio.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

/**
 * @author Zhou Feng
 */
public class FileChannelDemo01 {
    // FileChannel将数据读入buffer中
    public static void main(String[] args) {
        try(RandomAccessFile file = new RandomAccessFile("d:/a.txt", "rw");) {
            // 创建FileChannel

            FileChannel channel = file.getChannel();
            // 创建Buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 读取文件中的数据到buffer
            int readCount = channel.read(byteBuffer);

            ArrayList<Byte> res = new ArrayList<>();
            //等于 -1 则表示读完了
            while (readCount != -1) {
                System.out.printf("读取了： %d 字节\n", readCount);

                // 将写模式 转为 读模式 ， 从缓冲区读取数据
                // 设置 limit = position; position=0 ，以便读取刚刚写入的数据
                byteBuffer.flip();

                // 当缓冲区中有内容时,就读取
                while (byteBuffer.hasRemaining()) {
                    res.add(byteBuffer.get());
                }
                // 清空整个缓冲区, 重置缓冲区， limit = capacity; position = 0;
                byteBuffer.clear();
                //进行下一次读取
                readCount = channel.read(byteBuffer);
            }
            System.out.println("读完了。结果是：");
            byte[] resBytes = new byte[res.size()];
            for (int i = 0; i < res.size(); i++) {
                resBytes[i] = res.get(i);
            }
            System.out.println(new String(resBytes));
        } catch (IOException ignored){

        }
    }
}
